//
//  AXFSuperMarketViewController.m
//  AIXF
//
//  Created by Macx on 2017/7/9.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "AXFSuperMarketViewController.h"
#import <Masonry.h>
#import "AXFSuperMaketLeftTableViewCell.h"
#import "AXFSuperMarketRightTableViewCell.h"
#import "AXFSuperMarketModel.h"
#import "AXFHomeViewModel.h"
#import <UIImageView+WebCache.h>
#import "AXFAccountManager.h"
#import "AXFCellSelectedTableViewController.h"
#import <SVProgressHUD.h>
@interface AXFSuperMarketViewController ()<UITableViewDataSource, UITableViewDelegate,CAAnimationDelegate>

@property (nonatomic, weak) UITableView *leftTableView;

@property (nonatomic, weak) UITableView *rightTableView;

@property (nonatomic, strong) NSArray <AXFSuperMarketModel *> *leftArray;

@property (nonatomic, strong) NSArray <NSArray *> *rightArray;
@end
static NSString *left_id = @"left";

static NSString *right_id = @"right";


@implementation AXFSuperMarketViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = YES;
    
    self.navigationController.navigationBar.translucent = NO;
    
    self.leftArray = [AXFHomeViewModel shared].superMarketLeftModelArray;
    
    self.rightArray = [AXFHomeViewModel shared].superMarketRightModelArray;
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:250/255.0 green:203/255.0 blue:61/255.0 alpha:1];
    
    if (self.leftArray.count > 0 && self.rightArray.count > 0 ) {
        
        [self setupUI];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiceArray) name:@"postSuperMarketArray" object:nil];
    
      [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveIncrementNotification:) name:kIncrementRightNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveDecrementNotification:) name:kDecrementRightNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveNotification) name:@"postNum" object:nil];
   
}


- (void)setupUI
{
#pragma mark - 1. 添加左侧
    UITableView *leftTableView = [[UITableView alloc] init];

    _leftTableView = leftTableView;
    
    leftTableView.dataSource = self;
    
    leftTableView.delegate = self;
    
    leftTableView.rowHeight = 44;
    
    // 注册cell
    [leftTableView registerClass:[AXFSuperMaketLeftTableViewCell class] forCellReuseIdentifier:left_id];
    [self.view addSubview:leftTableView];
    
    // 约束
    [leftTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.leading.bottom.top.equalTo(self.view);
        
        //make.top.equalTo(self.view).offset(64);
        
       // make.top.mas_equalTo(64);
        
        make.width.mas_equalTo(100);
    }];
    
#pragma mark - 2. 右侧tableView
    
    UITableView *rightTableView = [[UITableView alloc] init];
    
    _rightTableView = rightTableView;
    
    rightTableView.dataSource = self;
    rightTableView.delegate = self;
    
    // 自动计算行高
   // rightTableView.estimatedRowHeight = 100;
    rightTableView.sectionHeaderHeight = 44;
    rightTableView.rowHeight = 122;
    
    [rightTableView registerNib:[UINib nibWithNibName:@"AXFSuperMarketRightTableViewCell" bundle:nil] forCellReuseIdentifier:right_id];
    
    [self.view addSubview:rightTableView];
    
    // 约束
    [rightTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 100, 0, 0));

    }];
    
}

- (void)receiceArray
{
    self.leftArray = [AXFHomeViewModel shared].superMarketLeftModelArray;
    
    [self setupUI];

    
    self.rightArray = [AXFHomeViewModel shared].superMarketRightModelArray;
    
    [self.leftTableView reloadData];
    
    [self.rightTableView reloadData];
    
}

- (void)didReceiveNotification{
    [SVProgressHUD showImage:[UIImage imageNamed:@"v2_about_logo"] status:@"库存商品不足"];
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UILabel *label = [[UILabel alloc] init];
    
    // 设置文本
    label.text = [NSString stringWithFormat:@"  %@", self.leftArray[section].name];
    
    // 修改背景颜色
    label.backgroundColor = [UIColor colorWithWhite:0.3 alpha:0];
    
    // 大小
    label.font = [UIFont systemFontOfSize:14];
    
    return label;
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    // 默认选中 左侧tableView的第0行
    [_leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
    
    // 刷新数据
    [_rightTableView reloadData];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == _leftTableView) {
        
        /**
         左侧tableView选中的行索引, 就是右侧tableView , 滚动到的 组索引
         */
        NSIndexPath *newPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.row];
        
        // 滚动
        [_rightTableView scrollToRowAtIndexPath:newPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    
        
    } else
    {
        AXFCellSelectedTableViewController *vc = [[AXFCellSelectedTableViewController alloc] init];
        
        vc.model = self.rightArray[indexPath.section][indexPath.row];
        
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 下面的代码只有通过手势拖拽 右侧tableView的时候才需要执行
    if (_rightTableView.isTracking || _rightTableView.isDragging || _rightTableView.isDecelerating) {
        
        
        if (tableView == _rightTableView) {
            
            // 可见cell的 indexPath 数组
            NSArray *indexPathArray = [tableView indexPathsForVisibleRows];
            
            // 获取数组中下标为0对应的元素
            NSIndexPath *desPath = indexPathArray.firstObject;
            
            // 需要修改左侧tableView 选中
            NSIndexPath *newPath = [NSIndexPath indexPathForRow:desPath.section inSection:0];
            
            // 修改左侧talbeView选中
            [_leftTableView selectRowAtIndexPath:newPath animated:YES scrollPosition:UITableViewScrollPositionTop];
            
        }
        
    }
    
    
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return _leftTableView == tableView ? 1 : self.leftArray.count;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   
    
    return _leftTableView == tableView ? self.leftArray.count : self.rightArray[section].count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  {
    
    if (tableView == _leftTableView) {
        
        AXFSuperMaketLeftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:left_id forIndexPath:indexPath];
        
        cell.backgroundColor = [UIColor groupTableViewBackgroundColor];
        
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    
        cell.textLabel.text = self.leftArray[indexPath.row].name;
        
        return cell;
    } else {
        
        AXFSuperMarketRightTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:right_id forIndexPath:indexPath];
        
        // 展示内容
        cell.rightModel = self.rightArray[indexPath.section][indexPath.row];
        
        return cell;
    }
}

//动画
- (void)didReceiveIncrementNotification:(NSNotification *)noti {
    
    CGPoint startPoint = [noti.userInfo[@"point"] CGPointValue];
    
    AXFHomeFirstSellModel *model = noti.userInfo[@"model"];
    
    if (![_AXFAccountManager.orderArray containsObject:model]) {
        // 如果数组中没有添加过这个对象就进行添加
        [_AXFAccountManager.orderArray addObject:model];
    }
    CGPoint controlPoint = CGPointMake(startPoint.x + 50, startPoint.y + 50);
    
    CGPoint endPoint = CGPointMake(_ScreenW / 4 * 2.5, _ScreenH - 44);
    
    UIImageView *imgIcon = [[UIImageView alloc] init];
    
    NSURL *imgUrl = [[NSURL alloc] initWithString:model.img];
    
    imgIcon.frame = CGRectMake(startPoint.x, startPoint.y, 100, 140);
    
    [imgIcon sd_setImageWithURL:imgUrl placeholderImage:[UIImage imageNamed:@"v2_placeholder_full_size"]];
    
    [kWindow addSubview:imgIcon];
    
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    
    [bezierPath moveToPoint:startPoint];
    
    [bezierPath addQuadCurveToPoint:endPoint controlPoint:controlPoint];
    
    // 关键帧动画
    CAKeyframeAnimation *keyFrame = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    
    // 设置路径
    keyFrame.path = bezierPath.CGPath;
    
    // 设置动画时间
    keyFrame.duration = 1;
    
    // 保持动画的最新状态
    keyFrame.removedOnCompletion = NO;
    
    keyFrame.fillMode = kCAFillModeBoth;
    
    CABasicAnimation *scaleFrame = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    scaleFrame.toValue = @0.3;
    scaleFrame.duration = 1;
    keyFrame.delegate = self;
    [keyFrame setValue:imgIcon forKey:@"imgIcon"];
    [imgIcon.layer addAnimation:keyFrame forKey:nil];
    [imgIcon.layer addAnimation:scaleFrame forKey:nil];
    
    _AXFAccountManager.goodsNum++;
    
}
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    
    // 获取传递的redBall, imageView
    UIImageView *imgIcon = [anim valueForKey:@"imgIcon"];
    
    [imgIcon removeFromSuperview];

}
- (void)didReceiveDecrementNotification:(NSNotification *)noti
{
    
      _AXFAccountManager.goodsNum--;
    // 取出模型
    AXFHomeFirstSellModel *rightModel = noti.object;
    
    if (rightModel.count == 0) {
        
        // 需要把这个模型对象从数组中移除
        [_AXFAccountManager.orderArray removeObject:rightModel];
    }
}
@end
